package com.youdianstar.app.common.widget

import android.content.Context
import android.text.Spannable
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.URLSpan
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.youdianstar.app.common.R


/**
 * File: ClickURLSpan
 * Author: 82149 Create: 2021/10/8 12:31
 * Changes (from 2021/10/8)
 * --------------------------------------------------
 * description: URL点击处理
 * ---------------------------------------------------
 *
 */
class ClickURLSpan(var context: Context, val url: String, val colorId:Int, val urlAction: (String) -> Unit) : URLSpan(url) {
    companion object {
        @JvmStatic
        fun textUnderline(textView: TextView, colorId:Int, urlAction: (String) -> Unit) {
            textView.movementMethod = LinkMovementMethod.getInstance()
            if (textView.text is Spannable) {
                val spannable = textView.text as Spannable
                val allSpans = spannable.getSpans(0, spannable.length, URLSpan::class.java)//查找<a></a>对应的URLSpan
                for (span in allSpans) {
                    val start = spannable.getSpanStart(span)
                    val end = spannable.getSpanEnd(span)
                    spannable.setSpan(ClickURLSpan(textView.context, span.url, colorId, urlAction), start, end, 0)//替换为自定义的ClickURLSpan

                    spannable.removeSpan(span)
                }
                textView.autoLinkMask = 0
                textView.text = spannable
            }
        }

    }

    override fun updateDrawState(ds: TextPaint) {
        super.updateDrawState(ds)
        //设置a链接颜色
        ds.setColor(ContextCompat.getColor(context, colorId))
        ds.linkColor = ContextCompat.getColor(context, colorId)
        //去掉a链接下划线
//        ds.isUnderlineText = false
    }

    override fun onClick(widget: View) {
        //super.onClick(widget)
        urlAction.invoke(url)
    }
}